import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from './user.service';
import { JwtService } from '@nestjs/jwt';
import * as argon2 from 'argon2';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, pw: string): Promise<any> {
    const userInfo = await this.usersService.getUserInfo(username);
    // 验证密码
    if (userInfo && (await argon2.verify(userInfo.user_pw, pw))) {
      const { user_pw, ...result } = userInfo;
      return result;
    } else {
      throw new UnauthorizedException('用户名或密码错误');
    }
  }

  async getToken(user) {
    const payload = {
      user_id: user.user_id,
      email: user.email,
      username: user.username,
      nickname: user.nickname,
    };
    return {
      userInfo: {
        nickname: user.nickname,
      },
      access_token: this.jwtService.sign(payload),
    };
  }
}
